package com.lsl.test1;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 银行有一一个账户。
 有两个储户分别向同-个账户存3000元，每次存1000，存3次。每次存完打
 印账户余额。

 * @author lishuailong
 * @create 2020-07-06 11:14
 */
public class 线程同步练习1 {
    public static void main(String[] args) {
        Depositor depositor = new Depositor();

        Thread thread = new Thread(depositor);
        Thread thread1 =new Thread(depositor);

        thread.setName("小明");
        thread1.setName("小红");

        thread.start();
        thread1.start();

    }
}
class Account{
    private int balance=0;
    Lock lock = new ReentrantLock();

   public  void addBalance(int qian){

       try {
           lock.lock();
           balance+=qian;
           Thread.sleep(100);
           System.out.println(Thread.currentThread().getName()+"存入"+qian+"，余额："+balance);

       } catch (InterruptedException e) {
           e.printStackTrace();
       }finally {
           lock.unlock();
       }
   }
}

class Depositor implements Runnable{
    private Account account=new Account();

    @Override
    public void run() {
        int i=10;
        while (i>0){
            account.addBalance(1000);
            i--;
        }

    }
}